package site.nullable.recorder.service

import android.content.Context
import android.media.MediaRecorder
import android.os.Build
import android.os.ParcelFileDescriptor
import java.io.IOException

class AudioRecorderService(private val context: Context) {
    private var mediaRecorder: MediaRecorder? = null
    private var isRecording = false
    private var fileDescriptor: ParcelFileDescriptor? = null

    fun startRecording(recording: site.nullable.recorder.data.model.Recording, fileDescriptor: ParcelFileDescriptor): Boolean {
        return try {
            this.fileDescriptor = fileDescriptor

            mediaRecorder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                MediaRecorder(context)
            } else {
                MediaRecorder()
            }.apply {
                setAudioSource(MediaRecorder.AudioSource.MIC)
                setOutputFormat(MediaRecorder.OutputFormat.MPEG_4)
                setAudioEncoder(MediaRecorder.AudioEncoder.AAC)
                setOutputFile(fileDescriptor.fileDescriptor)

                prepare()
                start()
            }

            isRecording = true
            true
        } catch (e: IOException) {
            e.printStackTrace()
            fileDescriptor.close()
            false
        } catch (e: IllegalStateException) {
            e.printStackTrace()
            fileDescriptor.close()
            false
        }
    }

    fun stopRecording(): Boolean {
        return try {
            mediaRecorder?.apply {
                stop()
                release()
            }
            mediaRecorder = null

            fileDescriptor?.close()
            fileDescriptor = null

            isRecording = false
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }

    fun getCurrentAmplitude(): Int {
        return try {
            mediaRecorder?.maxAmplitude ?: 0
        } catch (e: Exception) {
            0
        }
    }

    fun isRecording(): Boolean = isRecording
}